package com.itheima.reggie.controller;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {
    @Autowired  //调用service方法
    private EmployeeService employeeService;
    @Autowired //调用session
    private HttpSession session;
    //创建一个类 接收前端传递过来的用户名和密码
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String,String> map){
        String username = map.get("username");
        String password = map.get("password");
        //调用service进行登陆操作
       ResultInfo resultInfo= employeeService.login(username,password);
        //用户登录成功 想session中保存一个employee对象
        if(resultInfo.getCode()==1){
            //通过resultInfo 得到一个对象
           Employee employee= (Employee) resultInfo.getData();
            session.setAttribute(Constant.SESSION_EMPLOYEE,employee);
        }
        //返回对象
        return resultInfo;
    }
    //用户退出功能
    @PostMapping("/employee/logout")
    public ResultInfo loginOut(){
        //销毁session中的对象
        session.invalidate();
        return ResultInfo.success(null);
    }
    //用户名字匹配功能
    @GetMapping("/employee/find")
    public  ResultInfo findName(String name){
        List<Employee> employeeList = employeeService.findName(name);
        return ResultInfo.success(employeeList);
    }
    //用户添加功能
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee){
        //调用service save方法
        employeeService.save(employee);
        //返回一个Result值
        return ResultInfo.success(null);
    }
    //通过id查找
    @GetMapping("/employee/{id}")
    public  ResultInfo findById(@PathVariable("id") Long id){
        //调用service  方法查找id
       Employee employee=employeeService.findById(id);
       return ResultInfo.success(employee);
    }
    //修改方法
    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }
}
